package com.haoze.nurseapp.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonObject;
import com.haoze.common.dto.AgeDTO;
import com.haoze.common.enumeration.CirculationModelEnum;
import com.haoze.common.enumeration.CirculationTypeEnum;
import com.haoze.common.enumeration.ConstantEnum;
import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import com.haoze.common.utils.*;
import com.haoze.nurseapp.aop.NurseLogAop;
import com.haoze.nurseapp.component.PatientComponent;
import com.haoze.nurseapp.dao.*;
import com.haoze.nurseapp.dto.PatientExamDTO;
import com.haoze.nurseapp.enumeration.VarCodeEnum;
import com.haoze.nurseapp.model.CirculationLogEntity;
import com.haoze.nurseapp.model.PatientConfirmDateEntity;
import com.haoze.nurseapp.service.PatientService;
import com.haoze.nurseapp.vo.*;

import com.netflix.discovery.converters.Auto;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.rmi.MarshalledObject;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import java.util.stream.Collectors;

@Service
public class PatientServiceImpl implements PatientService {

    @Resource
    PatientMapper patientMapper;

    @Resource
    PatientInHospitalMapper patientInHospitalMapper;

    @Resource
    TransfusionMapper transfusionMapper;

    @Resource
    TaskExecuteMapper taskExecuteMapper;
    @Resource
    CirculationLogMapper circulationLogMapper;
    @Resource
    PatientComponent patientComponent;
    @Resource
    PatientConfirmDateMapper patientConfirmDateMapper;

    @Value("${his.url.environmentFlag}")
    private String environmentFlag;

    @Value("${his.url.cost}")
    private String cost;

    @Value("${his.url.operationUrl}")
    private String operationUrl;

    private static final Logger log = LoggerFactory.getLogger(NurseLogAop.class);

    @Value("${spring.profiles.active}")
    private String activeType;

    @Value("${his.url.query}")
    private String hisQueryUrl;

    @Value("${his.url.circulation}")
    private String circulationUrl;


    @Autowired
    private MealListMapper mealListMapper;


    @Override
    public Result getPatientInfoCards(Integer page, Integer pageSize, String wardId, String search) {
        PageHelper.startPage(page, pageSize);
        int total = 0;

        long time1 = System.currentTimeMillis();
        //获取deptId查询deptCode
        //城中                                                         //阳湖
        if ("95037CF5C9465245E053ED5B14ACFD88".equals(wardId) || "95037CF5C9475245E053ED5B14ACFD88".equals(wardId)) {
            //麻醉室
            List<Map<String, String>> deptList = new ArrayList<Map<String, String>>();
            Map<String, String> map = new HashMap<String, String>();
            map.put("recovery", "95037CF5C9465245E053ED5B14ACFD88");
            map.put("operation", "F0F3BC5868CE47F583CB08EC6E46B1D6");
            deptList.add(map);
            map = new HashMap<String, String>();
            map.put("recovery", "95037CF5C9475245E053ED5B14ACFD88");
            map.put("operation", "5D04523554944A30A5FB81F57E985763");
            deptList.add(map);
            String operationWardId = null;
            String deptCode = null;
            for (Map<String, String> dMap : deptList) {
                if (wardId.equals(dMap.get("recovery"))) {
                    operationWardId = dMap.get("operation");
                }
            }
            Map<String, String> deptInfo = patientMapper.getDeptCodeById(operationWardId);
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            if (deptInfo != null) {
                deptCode = deptInfo.get("deptCode").replace("H", "");
                //调用his
                Map<String, String> params = new HashMap<String, String>();
                params.put("as_patient_id", "");
                params.put("as_operating_room", deptCode);
                params.put("operationID", ConstantEnum.HIS_PATIENT_CENTER_10003.getKey());
                System.out.println(JSON.toJSONString(params));
                JSONObject jsonObject = HttpClientUtil.sendPost(operationUrl, params);
                if (jsonObject.isEmpty()) {
                    return ResultGenerator.genFailedResult("获取复苏室数据失败");
                }
                if (null != jsonObject) {
                    Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                    if (resInt < 0) {
                        //return ResultGenerator.genFailedResult("HIS接口调用失败");
                        //return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                    }
                }
                if (jsonObject.getString("data") != null) {
                    list = JSON.parseObject(jsonObject.getString("data"), new TypeReference<List<Map<String, String>>>() {
                    });
                    //查询条件 住院号和姓名
                    if (StringUtils.isNotBlank(search)) {
                        list = list.stream().filter(patient -> (patient.get("PATIENT_ID").indexOf(search) >= 0 || patient.get("name").indexOf(search) >= 0)).collect(Collectors.toList());
                    }
                    list.stream().forEach(patient -> {
                        //根据住院号查询patient_in_hospital表中数据
                        String inpatNum = patient.get("PATIENT_ID").toString() + "-1";
                        patient.put("inpatNum", inpatNum);
                        Map<String, String> patientMap = patientMapper.queryPatientByInpatNum(inpatNum);
                        if (patientMap != null) {
                            patient.putAll(patientMap);
                        }
                        patient.put("currentWardDeptName", deptInfo.get("deptName"));
                    });
                    if (!CollectionUtils.isEmpty(list)) {
                        //排序
                        list = list.stream().sorted(Comparator.comparing(PatientServiceImpl::comparingByBedNo)).collect(Collectors.toList());
                    }
                }
                for (Map<String, String> item : list) {
                    item.put("infoType", "anaesthesia");//其他
                }
                PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(list);
                return ResultGenerator.genOkResult(pageInfo);
            }
            //城中                                                             //阳湖
        } else if ("F0F3BC5868CE47F583CB08EC6E46B1D6".equals(wardId) || wardId.equals("5D04523554944A30A5FB81F57E985763")) {
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            String deptCode = null;
            //手术室
            Map<String, String> deptInfo = patientMapper.getDeptCodeById(wardId);
            if (deptInfo != null) {
                deptCode = deptInfo.get("deptCode").replace("H", "");
                //调用his
                Map<String, String> params = new HashMap<String, String>();
                params.put("as_patient_id", "");
                params.put("as_operating_room", deptCode);
                params.put("operationID", ConstantEnum.HIS_PATIENT_CENTER_10002.getKey());
                System.out.println(JSON.toJSONString(params));
                JSONObject jsonObject = HttpClientUtil.sendPost(operationUrl, params);
                if (jsonObject.isEmpty()) {
                    return ResultGenerator.genFailedResult("获取手术数据失败");
                }
                if (null != jsonObject) {
                    Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                    if (resInt < 0) {
                        //return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                    }
                }
                if (jsonObject.getString("data") != null) {
                    list = JSON.parseObject(jsonObject.getString("data"), new TypeReference<List<Map<String, String>>>() {
                    });
                    //查询条件 住院号和姓名
                    if (StringUtils.isNotBlank(search)) {
                        list = list.stream().filter(patient -> (patient.get("PATIENT_ID").indexOf(search) >= 0 || patient.get("name").indexOf(search) >= 0)).collect(Collectors.toList());
                    }
                    list.stream().forEach(patient -> {
                        //根据住院号查询patient_in_hospital表中数据
                        String inpatNum = patient.get("PATIENT_ID").toString() + "-1";
                        patient.put("inpatNum", inpatNum);
                        Map<String, String> patientMap = patientMapper.queryPatientByInpatNum(inpatNum);
                        if (patientMap != null) {
                            patient.putAll(patientMap);
                        }
                        patient.put("currentWardDeptName", deptInfo.get("deptName"));
                    });
                    if (!CollectionUtils.isEmpty(list)) {
                        //排序
                        list = list.stream().sorted(Comparator.comparing(PatientServiceImpl::comparingByBedNo)).collect(Collectors.toList());
                    }
                }
                for (Map<String, String> item : list) {
                    item.put("infoType", "operation");//其他
                }
                //排序
                PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(list);
                return ResultGenerator.genOkResult(pageInfo);
            }
        } else {
            long time3 = System.currentTimeMillis();
            List<String> inpatNums = new CopyOnWriteArrayList<>();
            List<Map<String, Object>> patientList = patientMapper.queryPatients(wardId, search);
            patientList.parallelStream().forEach(x -> {
                inpatNums.add(x.get("inpatNum").toString());
                x.put("infoType", "orther");//其他1
            });
            List<Map<String, String>> nursingGradeLists = new CopyOnWriteArrayList<>();
            List<Map<String, String>> disdaseStateLists = new CopyOnWriteArrayList<>();
            List<Map<String, String>> risklist = new CopyOnWriteArrayList<>();
            String dateTime = DateUtil.dateToString(new Date(),"yyyy-MM-dd");
            if(!CollectionUtils.isEmpty(patientList)) {
                //定义集合
                List<String> nursingGradeList = Arrays.asList(VarCodeEnum.IJHL.getVarCode(), VarCodeEnum.IJHLEK.getVarCode(), VarCodeEnum.IIJHL.getVarCode(),
                        VarCodeEnum.IIIJHLEK.getVarCode(), VarCodeEnum.IIIJHL.getVarCode(), VarCodeEnum.IIIJHLEK.getVarCode(),
                        VarCodeEnum.YJHL.getVarCode(), VarCodeEnum.EJHL.getVarCode(), VarCodeEnum.SJHL.getVarCode(),
                        VarCodeEnum.TJHL.getVarCode(), VarCodeEnum.TJHLEK.getVarCode(), VarCodeEnum.JHBFYJHL.getVarCode(),
                        VarCodeEnum.JHBFEJHL.getVarCode(), VarCodeEnum.JHBFTJHL.getVarCode());

                List<String> disdaseStateList = Arrays.asList(VarCodeEnum.BINGWEI.getVarCode(), VarCodeEnum.BINGZHONG.getVarCode());

                //List<Map<String, String>> nursingGradeLists = mealListMapper.queryNursingGradeByInpatNum(inpatNums, dateTime,nursingGradeList);
                //List<Map<String, String>> disdaseStateLists = mealListMapper.queryNursingGradeByInpatNum(inpatNums, dateTime,disdaseStateList);
                //List<Map<String, String>> risklist = patientMapper.queryHighRiskList(inpatNums);
                nursingGradeLists = mealListMapper.queryNursingGradeByInpatNum(inpatNums, dateTime, nursingGradeList);
                disdaseStateLists = mealListMapper.queryNursingGradeByInpatNum(inpatNums, dateTime, disdaseStateList);
                risklist = patientMapper.queryHighRiskList(inpatNums);
            }
            System.out.println("----------------------sql查询耗时:" + (System.currentTimeMillis() - time3));
            long t1 = System.currentTimeMillis();
//			ThreadPoolExecutor executor = ThreadUtil.getThreadPool2();
//			for(Map<String, Object> patient : patientList){
            List<Map<String, String>> finalNursingGradeLists = nursingGradeLists;
            List<Map<String, String>> finalDisdaseStateLists = disdaseStateLists;
            List<Map<String, String>> finalRisklist = risklist;
            patientList.parallelStream().forEach(patient -> {
                //查询过敏药物和过敏食物
                patient.put("allergicDrugs", patientMapper.queryAllergicDrugs((String) patient.get("inpatNum")));
                patient.put("eatingHabits", patientMapper.queryEatingHabits((String) patient.get("inpatNum")));
//				CompletableFuture<String> future = CompletableFuture.supplyAsync(new Supplier<String>() {
//					public String get() {
                String deptId = patient.get("deptId").toString();
                if (deptId.equals("95037CF5C9465245E053ED5B14ACFD88") || deptId.equals("95037CF5C9475245E053ED5B14ACFD88")) {
                    patient.put("infoType", "anaesthesia");//麻醉
                } else if (deptId.equals("F0F3BC5868CE47F583CB08EC6E46B1D6") || deptId.equals("5D04523554944A30A5FB81F57E985763")) {
                    patient.put("infoType", "operation");//手术
                } else {
                    patient.put("infoType", "orther");//其他
                }
                //费别 注释的是正式参数与返回
                String url = cost;
                Map<String, Object> param = new HashMap<>();
                param.put("as_patientId", patient.get("inpatNum").toString().replace("-1", ""));
                param.put("operationID", "10001");
                param.put("al_visitId", "1");
                param.put("al_doctor_type", "");
                long time2 = System.currentTimeMillis();
                Future<JSONObject> future = ThreadUtil.submit(() -> HttpClientUtil.sendPost(url, param));
//						CompletableFuture<String> ordedCustomerFuture = CompletableFuture.supplyAsync(() ->
//								HttpClientUtil.sendPost(url, param)).thenApply(x -> x.toString());
                long time22 = System.currentTimeMillis();
                System.out.println("-------------------------------------------------his当前耗时2:" + (time22 - t1));
                patient.put("age", getPatientAgeOPbject(patient));
                if (inpatNums != null && inpatNums.size() > 0) {
                    List<Map<String, String>> riskList2 = new CopyOnWriteArrayList<>();
                    finalRisklist.forEach(riskItem -> {
                        if (riskItem.get("INPAT_NUM").equals(patient.get("inpatNum"))) {
                            riskList2.add(riskItem);
                        }
                    });
                    patient.put("highRiskList", dealRisk(riskList2));
                }

                if (patient.get("nursingGrade") == null) {
                    patient.put("nursingGrade", "");
                }
                /*if (patient.get("disdaseState") == null) {
                    patient.put("disdaseState", "一般");
                }*/
                if (patient.get("allergicDrugs") == null) {
                    patient.put("allergicDrugs", "");//过敏药物信息
                }else{
                    patient.put("allergicDrugs", toRepeatList((String)patient.get("allergicDrugs")));
                }
                if (patient.get("disdaseState") == null) {
                    patient.put("disdaseState", "");//病情
                }
                /*if (patient.get("nursingGrade") == null) {
                    patient.put("nursingGrade", "");//护理等级
                }*/
                if (patient.get("eatingHabits") == null) {
                    patient.put("eatingHabits", "");//饮食习惯 (饮食过敏史)
                }else{
                    patient.put("eatingHabits", toRepeatList((String)patient.get("eatingHabits")));
                }
                if (patient.get("drugBacterialInfection") == null) {
                    patient.put("drugBacterialInfection", "0");//多重耐药菌感染信息
                }
                if (patient.get("responsibleNursePerson") == null) {
                    patient.put("responsibleNursePerson", "");// 责任护士
                }
                //护理等级
                Map<String, String> filterNursingGrade = finalNursingGradeLists.stream().filter(s -> ((String)patient.get("inpatNum")).equals(s.get("inpatNum"))).findFirst().orElse(null);
                if(filterNursingGrade!=null){
                    //监护病房特级护理，特级护理，特级护理（儿科）
                    //Ⅰ级护理，Ⅰ级护理（儿科），一级护理 监护病房一级护理
                    //ⅠⅠ级护理，ⅠⅠ级护理（儿科），二级护理 监护病房二级护理
                    //ⅠⅠⅠ级护理，ⅠⅠⅠ级护理（儿科），三级护理
                    if(VarCodeEnum.TJHL.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.TJHLEK.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.JHBFTJHL.getVarCode().equals(filterNursingGrade.get("varCode"))){
                        patient.put("nursingGrade",VarCodeEnum.TJHL.getName());
                    }else if(VarCodeEnum.IJHL.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.IJHLEK.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.YJHL.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.JHBFYJHL.getVarCode().equals(filterNursingGrade.get("varCode"))){
                        patient.put("nursingGrade",VarCodeEnum.YJHL.getName());
                    }else if(VarCodeEnum.IIJHL.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.IIJHLEK.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.EJHL.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.JHBFEJHL.getVarCode().equals(filterNursingGrade.get("varCode"))){
                        patient.put("nursingGrade",VarCodeEnum.EJHL.getName());
                    }else if(VarCodeEnum.IIIJHL.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.IIIJHLEK.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.SJHL.getVarCode().equals(filterNursingGrade.get("varCode"))){
                        patient.put("nursingGrade",VarCodeEnum.SJHL.getName());
                    }
                }else{
                    patient.put("nursingGrade", "");
                }
                //病情
                Map<String, String> filterdisdaseState = finalDisdaseStateLists.stream().filter(s -> ((String)patient.get("inpatNum")).equals(s.get("inpatNum"))).findFirst().orElse(null);
                if(filterdisdaseState!=null){
                    //监护病房特级护理，特级护理，特级护理（儿科）
                    //Ⅰ级护理，Ⅰ级护理（儿科），一级护理 监护病房一级护理
                    //ⅠⅠ级护理，ⅠⅠ级护理（儿科），二级护理 监护病房二级护理
                    //ⅠⅠⅠ级护理，ⅠⅠⅠ级护理（儿科），三级护理
                    if(VarCodeEnum.BINGWEI.getVarCode().equals(filterdisdaseState.get("varCode"))){
                        patient.put("disdaseState",VarCodeEnum.BINGWEI.getName());
                    }else if(VarCodeEnum.BINGZHONG.getVarCode().equals(filterdisdaseState.get("varCode"))){
                        patient.put("disdaseState",VarCodeEnum.BINGZHONG.getName());
                    }else{
                        patient.put("disdaseState", "一般");
                    }
                }else{
                    patient.put("disdaseState", "一般");
                }

                try {
                    JSONObject jsonObject = future.get();
//							while(jsonObject == null){
//								if((System.currentTimeMillis()-time2)>1000){
//									jsonObject = new JSONObject();
//								}else if(ordedCustomerFuture.isDone()){
//
//								}
//							}
                    if (jsonObject.get("data") == null) {
                        patient.put("payOff", "");
                    } else {
                        if (jsonObject.getString("data") != null) {
                            if (JSONArray.parseArray(jsonObject.getString("data"), Map.class).size() != 0) {
                                Map costItem = JSONArray.parseArray(jsonObject.getString("data"), Map.class).get(0);
                                if (costItem.get("CHARGE_TYPE").toString().contains("自费")) {
                                    patient.put("payOff", "自费");
                                } else {
                                    patient.put("payOff", costItem.get("CHARGE_TYPE").toString());
                                }
                            } else {
                                patient.put("payOff", "");
                            }
                        }
                    }
                    long time4 = System.currentTimeMillis();
                    System.out.println("调用HIS接口获取费用明细耗时：：：：：：：：：：：：：：：" + (time4 - time2));
                    log.info("调用HIS接口获取费用明细耗时：：：：：：：：：：：：：：：{}ms", (time4 - time2));
                } catch (Exception e) {
                    patient.put("payOff", "");
                    log.error("查询费用明细失败", e);
                }
//					}
//				}, executor);
//			}
            });

//			patientList.sort((a, b) -> new BigDecimal(a.get("bedNo").toString())
//					.intValue() - new BigDecimal(b.get("bedNo").toString()).intValue());
            PageInfo pageInfo = new PageInfo(patientList);
            return ResultGenerator.genOkResult(pageInfo);
        }

        PageInfo pageInfoEmpty = new PageInfo();
        pageInfoEmpty.setList(new ArrayList());
        pageInfoEmpty.setTotal(total);
        return ResultGenerator.genOkResult(pageInfoEmpty);
    }

    public String toRepeatList(String data){
        List<String> list = new CopyOnWriteArrayList<>();
        if(StringUtils.isNotBlank(data)){
            for(String a1:data.split(",")){
                if(!list.contains(a1)){
                    list.add(a1);
                }
            }
            return StringUtils.join(list,",");

        }else{
            return "";
        }
    }

    private static String comparingByBedNo(Map<String, String> map) {
        return map.get("ROOM_NO");
    }

    @Override
    public Result getPatientInfo(String qrCode) {
        String inpatNum = taskExecuteMapper.queryInpatNumByQrcode(qrCode);
        if (StringUtils.isBlank(inpatNum)) {
            inpatNum = transfusionMapper.queryInfoByBarCode(qrCode);
        }
        //根据入院号获取当前病人信息（姓名，入院号，年龄，床号，性别）
        Map<String, String> patientMap = this.getPatientInfoWithComputeAge(inpatNum);
        return ResultGenerator.genOkResult(patientMap);
    }

    public String getCurrentDiagName(String inpatNum) {
        // 过滤诊断
        // 获取护士修改后绑定到文书的诊断id
        String diagName = "";
        String diagId = circulationLogMapper.queryDiagIdByInpatNum(inpatNum);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(diagId)) {
            // 获取护士修改的诊断名称
            diagName = circulationLogMapper.queryDiagByDiagId(diagId);
            return diagName;
        } else {
            //取病案首页his出院诊断
            if ("prod".equals(activeType)) {
                String[] inpatNums = inpatNum.split("-");
                String param = "as_patient_id=" + inpatNums[0] + "&al_visit_id=" + inpatNums[1];
                JSONObject jsonObject = HttpConnectUtils.sendGet("http://172.20.91.56:8181/P_VsitInfo_Query_03", param);
                if ("1".equals(jsonObject.get("error_id").toString())) {
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    for (Object jsonObject1 : jsonArray) {
                        JSONObject object = JSONObject.parseObject(jsonObject1.toString());
                        if (object.get("DIAGNOSIS_TYPE") != null && "2".equals(object.get("DIAGNOSIS_TYPE").toString())) {
                            diagName = object.get("DIAGNOSIS_DESC").toString();
                            break;
                        }
                    }
                }
            }
            if (org.apache.commons.lang3.StringUtils.isNotBlank(diagName)) {
                return diagName;
            } else {
                // 获取智慧病历出院诊断/修正诊断/入院诊断
                diagName = circulationLogMapper.queryOutHospitalDiag(inpatNum);
                if (org.apache.commons.lang3.StringUtils.isNotBlank(diagName)) {
                    return diagName;
                } else {
                    //获取his门诊诊断
                    diagName = circulationLogMapper.queryOutpatientDiag(inpatNum);
                    return diagName;
                }
            }
        }
    }

    @Override
    public Result conditionInfo(String inpatNum, String wardId) {
        //根据入院号获取当前病人信息（姓名，入院号，年龄，床号，性别）
        Map<String, String> patientMap = this.getPatientInfoWithComputeAge(inpatNum);
        if (patientMap == null) {
            return ResultGenerator.genFailedResult("无此住院病人信息");
        }

        patientMap.put("religiousBelief", patientMap.get("religion"));//宗教信仰
        patientMap.put("drugBacterialInfection", "无");//多重耐药菌感染信息
        patientMap.put("allergicDrugs", "无");//过敏药物信息
        patientMap.put("highRisk", "无");//病人高危信息

        patientMap.put("familyHistory", "无");//家族史
        patientMap.put("operationHistory", "无");//手术史
        patientMap.put("disease", "无");//曾患疾病
        patientMap.put("smokingHistory", "无");//吸烟史
        patientMap.put("drinkingHistory", "无");//饮酒史
        patientMap.put("eatingHabits", "无");//饮食习惯
        patientMap.put("supportSystem", "无");//支持系统
        patientMap.put("hospitalConcerns", "无");//住院顾虑
        patientMap.put("degreeEducation", patientMap.get("education"));//文化程度
        patientMap.put("height", "无");//身高
        patientMap.put("weight", "无");//体重

        String url = cost;
        Map<String, Object> param = new HashMap<>();
        param.put("as_patientId", inpatNum.replace("-1", ""));
        param.put("operationID", "10001");
        param.put("al_visitId", "1");
        param.put("al_doctor_type", "");
        CompletableFuture<String> ordedCustomerFuture = CompletableFuture.supplyAsync(() ->
                HttpClientUtil.sendPost(url, param)).thenApply(x -> x.toString());
        try {
            JSONObject jsonObject = JSON.parseObject(ordedCustomerFuture.get());
            if (jsonObject.getString("data") != null) {
                Map cost = JSONArray.parseArray(jsonObject.getString("data"), Map.class).get(0);
                if (cost.get("YE_JE") != null) {//余额
                    BigDecimal state = new BigDecimal(cost.get("YE_JE").toString());
                    patientMap.put("payOffState", state.toString());
                } else {
                    patientMap.put("payOffState", "0");
                }
                if (cost.get("YJJ_AMT") != null && StringUtils.isNotBlank(cost.get("YJJ_AMT").toString())) {//预交金总额
                    BigDecimal state = new BigDecimal(cost.get("YJJ_AMT").toString());
                    patientMap.put("yjjAmt", state.toString());
                } else {
                    patientMap.put("yjjAmt", "0");
                }
                if (cost.get("ZL_JE") != null && StringUtils.isNotBlank(cost.get("ZL_JE").toString())) {//自理现金
                    BigDecimal state = new BigDecimal(cost.get("ZL_JE").toString());
                    patientMap.put("zlJe", state.toString());
                } else {
                    patientMap.put("zlJe", "0");
                }
                if (cost.get("TOTAL_COST") != null && StringUtils.isNotBlank(cost.get("TOTAL_COST").toString())) {//未结总费用
                    BigDecimal state = new BigDecimal(cost.get("TOTAL_COST").toString());
                    patientMap.put("totalCost", state.toString());
                } else {
                    patientMap.put("totalCost", "0");
                }
                if (cost.get("CHARGE_TYPE").toString().contains("自费")) {
                    patientMap.put("payOff", "自费");
                } else {
                    patientMap.put("payOff", cost.get("CHARGE_TYPE").toString());
                }
            }
        } catch (Exception e) {
            log.error("查询费用明细失败", e);
        }

        // 获取血型
        patientComponent.componentBlood(patientMap);
        patientMap.put("bloodType", "");

        //入院诊断取最新值
//		String admissionDiagnosis = "";//入院诊断
//		List<Map<String,String>> admission = transfusionMapper.queryAdmissionDiagnosis(inpatNum);
//		for(int i=0;i<admission.size();i++){
//			Map<String,String> item = admission.get(i);
//			admissionDiagnosis += i+1 +"."+item.get("DATA_VALUE")+";\n";
//		}
//		if(StringUtils.isNotBlank(admissionDiagnosis))
//			patientMap.put("admissionDiagnosis", admissionDiagnosis);

        String bedno = patientMap.get("wardDept");
        // 处理床号,当出院病人床号为0时显示最近一次护理记录单中记录的床号
        if ("0".equals(bedno)) {
            // 获取记录时间最近的护理记录，从中获取床号
            bedno = patientMapper.getLatestBedNo(inpatNum);
            if (StringUtils.isNotEmpty(bedno)) {
                patientMap.put("wardDept", bedno);
            }
        }

        //获取手术信息
        if ("95037CF5C9465245E053ED5B14ACFD88".equals(wardId) || "95037CF5C9475245E053ED5B14ACFD88".equals(wardId)) {
            //调用his
            Map<String, String> params = new HashMap<String, String>();
            params.put("as_patient_id", inpatNum.split("-")[0]);
            params.put("as_operating_room", "");
            params.put("operationID", ConstantEnum.HIS_PATIENT_CENTER_10003.getKey());
            System.out.println(JSON.toJSONString(params));
            JSONObject jsonObject = HttpClientUtil.sendPost(operationUrl, params);
            if (jsonObject.isEmpty()) {
                //return ResultGenerator.genFailedResult("获取手术数据失败");
            }
            if (null != jsonObject) {
                Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                if (resInt < 0) {
                    //return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                }
            }
            if (jsonObject.getString("data") != null) {
                List<Map<String, String>> list = JSON.parseObject(jsonObject.getString("data"), new TypeReference<List<Map<String, String>>>() {
                });
                if (!CollectionUtils.isEmpty(list)) {
                    patientMap.putAll(list.get(0));
                    if (StringUtils.isNotBlank(list.get(0).get("IN_PACU_DATE_TIME"))) {
                        patientMap.put("IN_DATE_TIME", list.get(0).get("IN_PACU_DATE_TIME").substring(0, 16));
                    }
                }
            }
            //城中                                                             //阳湖
        } else if ("F0F3BC5868CE47F583CB08EC6E46B1D6".equals(wardId) || "5D04523554944A30A5FB81F57E985763".equals(wardId)) {
            //调用his
            Map<String, String> params = new HashMap<String, String>();
            params.put("as_patient_id", inpatNum.split("-")[0]);
            params.put("as_operating_room", "");
            params.put("operationID", ConstantEnum.HIS_PATIENT_CENTER_10002.getKey());
            System.out.println(JSON.toJSONString(params));
            JSONObject jsonObject = HttpClientUtil.sendPost(operationUrl, params);
            if (jsonObject.isEmpty()) {
                //return ResultGenerator.genFailedResult("获取手术数据失败");
            }
            if (null != jsonObject) {
                Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                if (resInt < 0) {
                    //return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                }
            }
            if (jsonObject.getString("data") != null) {
                List<Map<String, String>> list = JSON.parseObject(jsonObject.getString("data"), new TypeReference<List<Map<String, String>>>() {
                });
                if (!CollectionUtils.isEmpty(list)) {
                    patientMap.putAll(list.get(0));
                    if (StringUtils.isNotBlank(list.get(0).get("IN_DATE_TIME"))) {
                        patientMap.put("IN_DATE_TIME", list.get(0).get("IN_DATE_TIME").substring(0, 16));
                    }
                }
            }
        }
        Map result = new HashMap();
        result.putAll(patientMap);
        result.putAll(getIdentification(inpatNum));//护理登记  病重 药物过敏 危险标识
        //result.put("currentDiagnosis",getDiagName(inpatNum));
        //实时获取诊断
        String diagName = this.getCurrentDiagName(inpatNum);
        if (StringUtils.isNotBlank(diagName)) {
            result.put("currentDiagnosis", diagName);
        }
        String dateTime = DateUtil.dateToString(new Date(),"yyyy-MM-dd");
        List<String> nursingGradeList = Arrays.asList(VarCodeEnum.IJHL.getVarCode(), VarCodeEnum.IJHLEK.getVarCode(), VarCodeEnum.IIJHL.getVarCode(),
                VarCodeEnum.IIIJHLEK.getVarCode(), VarCodeEnum.IIIJHL.getVarCode(), VarCodeEnum.IIIJHLEK.getVarCode(),
                VarCodeEnum.YJHL.getVarCode(), VarCodeEnum.EJHL.getVarCode(), VarCodeEnum.SJHL.getVarCode(),
                VarCodeEnum.TJHL.getVarCode(), VarCodeEnum.TJHLEK.getVarCode(), VarCodeEnum.JHBFYJHL.getVarCode(),
                VarCodeEnum.JHBFEJHL.getVarCode(), VarCodeEnum.JHBFTJHL.getVarCode());
        List<String> disdaseStateList = Arrays.asList(VarCodeEnum.BINGWEI.getVarCode(), VarCodeEnum.BINGZHONG.getVarCode());
        List<Map<String, String>> nursingGradeLists = mealListMapper.queryNursingGradeByInpatNum(Arrays.asList(inpatNum), dateTime,nursingGradeList);
        List<Map<String, String>> disdaseStateLists = mealListMapper.queryNursingGradeByInpatNum(Arrays.asList(inpatNum), dateTime,disdaseStateList);
        AtomicReference<String> nursingGrade= new AtomicReference<>("无");
        nursingGradeLists.forEach(filterNursingGrade -> {
            if (VarCodeEnum.TJHL.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.TJHLEK.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.JHBFTJHL.getVarCode().equals(filterNursingGrade.get("varCode"))) {
                nursingGrade.set(VarCodeEnum.TJHL.getName());
            } else if (VarCodeEnum.IJHL.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.IJHLEK.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.YJHL.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.JHBFYJHL.getVarCode().equals(filterNursingGrade.get("varCode"))) {
                nursingGrade.set(VarCodeEnum.YJHL.getName());
            } else if (VarCodeEnum.IIJHL.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.IIJHLEK.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.EJHL.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.JHBFEJHL.getVarCode().equals(filterNursingGrade.get("varCode"))) {
                nursingGrade.set(VarCodeEnum.EJHL.getName());
            } else if (VarCodeEnum.IIIJHL.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.IIIJHLEK.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.SJHL.getVarCode().equals(filterNursingGrade.get("varCode"))) {
                nursingGrade.set(VarCodeEnum.SJHL.getName());
            }
        });
        AtomicReference<String> disdaseState= new AtomicReference<>("一般");
        disdaseStateLists.forEach(filterDisdaseState-> {
            if(VarCodeEnum.BINGWEI.getVarCode().equals(filterDisdaseState.get("varCode"))){
                disdaseState.set(VarCodeEnum.BINGWEI.getName());
            }else if(VarCodeEnum.BINGZHONG.getVarCode().equals(filterDisdaseState.get("varCode"))){
                disdaseState.set(VarCodeEnum.BINGZHONG.getName());
            }
        });

        result.put("nursingGrade", nursingGrade.get());//病人高危信息
        result.put("disdaseState", disdaseState.get());//病人高危信息

        return ResultGenerator.genOkResult(result);
    }

    public Map<String, Object> getIdentification(String inpatNum) {
        Map<String, Object> patientMap = new HashMap<>();
        Map<String, String> conditions = new HashMap<>();
        List<Map<String, String>> condList = patientMapper.queryConditionInfo(inpatNum);//护理登记  病重 药物过敏 危险标识
        for (Map<String, String> cond : condList) {
            if (cond != null) {
                if ("drugBacterialInfection".equals(cond.get("type"))) {
                    conditions.put("drugBacterialInfection", cond.get("data"));
                }
                /*else if ("nursingGrade".equals(cond.get("type"))) {
                    conditions.put("nursingGrade", cond.get("data"));
                }*/
                else if ("responsibleNursePerson".equals(cond.get("type"))) {
                    conditions.put("responsibleNursePerson", cond.get("data"));
                } else if ("disdaseState".equals(cond.get("type"))) {
                    conditions.put("disdaseState", cond.get("data"));
                } else if ("allergicDrugs".equals(cond.get("type"))) {
                    conditions.put("allergicDrugs", toRepeatList(cond.get("data")));
                } else if ("eatingHabits".equals(cond.get("type"))) {
                    conditions.put("eatingHabits", toRepeatList(cond.get("data")));
                }
            }
        }
        List<Map<String, String>> highRiskListOral = patientMapper.queryHighRisk(inpatNum);//高危信息
//		List<Map<String,String>> highRiskListOral = new CopyOnWriteArrayList<>();
//		highRiskLisData.parallelStream().forEach(x ->{
//			if("0b7448e0ced74d1c9ac9c97b0fc7a6ee".equals(x.get("ELEMENT_ID"))){
//				highRiskLisData.parallelStream().forEach(x2 ->{
//					if(x.get("FILE_DATA_ID").equals(x2.get("FILE_DATA_ID")) && x.get("PARENT_ID").equals(x2.get("PARENT_ID")) && "8ceb62574f344a7cb6aae91badba641f".equals(x2.get("ELEMENT_ID"))){
//						Map<String,String> item = new HashMap<>();
//						item.put("fileDate",x.get("fileDate"));
//						item.put("fileDateModify",x.get("gmtModify"));
//						item.put("highRisk",x2.get("highRisk"));
//						if(x.get("DATA_VALUE") ==null){
//							item.put("tplName","");
//						}else{
//							item.put("tplName",x.get("DATA_VALUE"));
//						}
//						highRiskListOral.add(item);
//					}
//				});
//			}
//		});
        Map<String, List<Map<String, String>>> bookMap = null;
        List<Map<String, String>> highRiskList = new ArrayList<>();
        if (highRiskListOral != null && highRiskListOral.size() > 0) {
            bookMap = highRiskListOral.stream().collect(Collectors.groupingBy(b -> b.get("tplName")));
            for (String key : bookMap.keySet()) {
                List<Map<String, String>> keyItem = bookMap.get(key);
                keyItem.sort((a, b) -> (int) (DateUtil.stringToDate(b.get("fileDateModify"), "yyyy-MM-dd HH:mm:ss").getTime() / 1000) - (int) (DateUtil.stringToDate(a.get("fileDateModify"), "yyyy-MM-dd HH:mm:ss").getTime() / 1000));
                if (keyItem != null && keyItem.size() > 0) {
                    highRiskList.add(keyItem.get(0));
                }
            }
        }

        if (conditions == null) {
            conditions = new HashMap<>();
        }

        List<Map<String, String>> riskList = new CopyOnWriteArrayList();
        highRiskList.parallelStream().forEach(item -> {
            if (StringUtils.isNotBlank(item.get("highRisk")) && StringUtils.isNotBlank(item.get("tplName"))) {
                Map<String, String> riskMap = new HashMap<>();
                if (item.get("highRisk") != null) {//危险程度
                    Integer score = Integer.parseInt(item.get("highRisk").toString());
                    if (score < 25) {
                        riskMap.put("highRisk", "低危");
                    } else if (score >= 25 && score <= 45) {
                        riskMap.put("highRisk", "中危");
                    } else if (score > 45) {
                        riskMap.put("highRisk", "高危");
                    }
                } else {
                    riskMap.put("highRisk", "无");
                }

                riskMap.put("fileDate", item.get("fileDate"));
                riskMap.put("highRiskData", item.get("highRisk"));
                riskMap.put("fileDateModify", item.get("fileDateModify"));
                riskMap.put("tplName", item.get("tplName"));
                String tplName = item.get("tplName");
                Integer score = Integer.parseInt(item.get("highRisk"));
                if (item.get("highRisk") != null) {//危险程度
                    if ("Morse跌倒评分".equals(tplName)) {//跌倒
                        if (score >= 45) {
                            riskMap.put("highRisk", "高危");
                        } else if (score >= 25 && score <= 44) {
                            riskMap.put("highRisk", "中危");
                        } else if (score < 25) {
                            riskMap.put("highRisk", "高危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("儿童跌倒/坠床评分".equals(tplName)) {//跌倒
                        if (score >= 12) {
                            riskMap.put("highRisk", "高危");
                        } else if (score < 12) {
                            riskMap.put("highRisk", "低危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("Braden评分".equals(tplName)) {//braden
                        if (score <= 9) {
                            riskMap.put("highRisk", "高危");//极高危
                        } else if (score >= 10 && score <= 12) {
                            riskMap.put("highRisk", "高危");
                        } else if (score >= 13 && score <= 14) {
                            riskMap.put("highRisk", "中危");
                        } else if (score >= 15 && score <= 18) {
                            riskMap.put("highRisk", "低危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("Braden-Q评分".equals(tplName) && (score <= 10 || (score >= 11 && score <= 16))) {
                        if (score <= 10) {
                            riskMap.put("highRisk", "高危");//极高危
                        } else if (score >= 11 && score <= 16) {
                            riskMap.put("highRisk", "高危");
                        } else if (score >= 17 && score <= 21) {
                            riskMap.put("highRisk", "中危");
                        } else if (score >= 22) {
                            riskMap.put("highRisk", "低危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("Barthel评分".equals(tplName) && score <= 40) {
                        if (score <= 40) {
                            riskMap.put("highRisk", "高危");//重度依赖
                        } else if (score >= 41 && score <= 60) {
                            riskMap.put("highRisk", "中危");//中度依赖
                        } else if (score >= 61 && score <= 99) {
                            riskMap.put("highRisk", "低危");//轻度依赖
                        } else if (score == 100) {
                            riskMap.put("highRisk", "");//无需依赖
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("营养风险筛查NRS2002评分".equals(tplName) && score >= 3) {
                        if (score >= 3) {
                            riskMap.put("highRisk", "高危");//重度
                        } else if (score == 2) {
                            riskMap.put("highRisk", "中危");//中度
                        } else if (score == 1) {
                            riskMap.put("highRisk", "低危");//轻度
                        } else if (score == 0) {
                            riskMap.put("highRisk", "");//正常
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("导管滑脱危险因素评分".equals(tplName) && score > 12) {
                        if (score > 12) {
                            riskMap.put("highRisk", "高危");
                        } else if (score >= 8 && score <= 12) {
                            riskMap.put("highRisk", "中危");
                        } else if (score < 8) {
                            riskMap.put("highRisk", "低危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("Caprini评分".equals(tplName) && (score >= 5 || (score >= 3 && score <= 4))) {
                        if (score >= 5) {
                            riskMap.put("highRisk", "高危");
                        } else if (score >= 3 && score <= 4) {
                            riskMap.put("highRisk", "中危");
                        } else if (score >= 1 && score <= 2) {
                            riskMap.put("highRisk", "低危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    }else if ("Padua评分".equals(tplName) && (score >= 4 || (score >= 0 && score <= 3))) {
                        if (score >= 4) {
                            riskMap.put("highRisk", "高危");
                        } else if (score >= 0 && score <= 3) {
                            riskMap.put("highRisk", "低危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    }
                } else {
                    riskMap.put("highRisk", "");
                }
                if ("Morse跌倒评分".equals(tplName) && score >= 45) {//跌倒
                    riskMap.put("highRiskName", "跌");
                } else if ("儿童跌倒/坠床评分".equals(tplName) && score >= 12) {//跌倒
                    riskMap.put("highRiskName", "跌");
                } else if ("Braden评分".equals(tplName) && (score <= 9 || (score >= 10 && score <= 12) || (score >= 13 && score <= 14))) {//braden
                    riskMap.put("highRiskName", "压");
                } else if ("Braden-Q评分".equals(tplName) && (score <= 10 || (score >= 11 && score <= 16) || (score >= 17 && score <= 21))) {
                    riskMap.put("highRiskName", "压");
                } else if ("Barthel评分".equals(tplName) && score <= 40) {
                    riskMap.put("highRiskName", "自");
                } else if ("营养风险筛查NRS2002评分".equals(tplName) && score >= 3) {
                    riskMap.put("highRiskName", "");
                } else if ("导管滑脱危险因素评分".equals(tplName) && score > 12) {
                    riskMap.put("highRiskName", "管");
                } else if (("Caprini评分".equals(tplName) && (score >= 5 || (score >= 3 && score <= 4))) || ("Padua评分".equals(tplName) && score >= 4) ) {
                    riskMap.put("highRiskName", "栓");
                } else {
                    riskMap.put("highRiskName", "");
                }
                if (StringUtils.isNotBlank(riskMap.get("highRiskName"))) {
                    riskList.add(riskMap);
                }
            }
        });
        if (riskList != null && riskList.size() > 0) {
            riskList.sort((a, b) -> (int) (DateUtil.stringToDate(a.get("fileDateModify"), "yyyy-MM-dd HH:mm:ss").getTime() / 1000) - (int) (DateUtil.stringToDate(b.get("fileDateModify"), "yyyy-MM-dd HH:mm:ss").getTime() / 1000));
        }
        patientMap.put("highRiskList", riskList);
        patientMap.putAll(conditions);
        if (StringUtils.isBlank(conditions.get("allergicDrugs"))) {
            patientMap.put("allergicDrugs", "无");//过敏药物信息
        }
        if (StringUtils.isBlank(conditions.get("disdaseState"))) {
            patientMap.put("disdaseState", "一般");//病情
        }
        if (StringUtils.isBlank(conditions.get("nursingGrade"))) {
            patientMap.put("nursingGrade", "无");//护理等级
        }
        if (StringUtils.isBlank(conditions.get("eatingHabits"))) {
            patientMap.put("eatingHabits", "无");//饮食习惯 (饮食过敏史)
        }
        if (StringUtils.isBlank(conditions.get("drugBacterialInfection"))) {
            patientMap.put("drugBacterialInfection", "0");//多重耐药菌感染信息
        }
        if (StringUtils.isBlank(conditions.get("responsibleNursePerson"))) {
            patientMap.put("responsibleNursePerson", "无");//责任护士
        }
        return patientMap;
    }

    public List<Map<String, String>> dealRisk(List<Map<String, String>> highRiskListOral) {
        Map<String, List<Map<String, String>>> bookMap = null;
        List<Map<String, String>> highRiskList = new ArrayList<>();
        if (highRiskListOral != null && highRiskListOral.size() > 0) {
            bookMap = highRiskListOral.stream().collect(Collectors.groupingBy(b -> b.get("tplName")));
            for (String key : bookMap.keySet()) {
                List<Map<String, String>> keyItem = bookMap.get(key);
                keyItem.sort((a, b) -> (int) (DateUtil.stringToDate(b.get("fileDateModify"), "yyyy-MM-dd HH:mm:ss").getTime() / 1000) - (int) (DateUtil.stringToDate(a.get("fileDateModify"), "yyyy-MM-dd HH:mm:ss").getTime() / 1000));
                if (keyItem != null && keyItem.size() > 0) {
                    highRiskList.add(keyItem.get(0));
                }
            }
        }
        List<Map<String, String>> riskList = new CopyOnWriteArrayList();
        highRiskList.parallelStream().forEach(item -> {
            if (StringUtils.isNotBlank(item.get("highRisk")) && StringUtils.isNotBlank(item.get("tplName"))) {
                Map<String, String> riskMap = new HashMap<>();
                if (item.get("highRisk") != null) {//危险程度
                    Integer score = Integer.parseInt(item.get("highRisk").toString());
                    if (score < 25) {
                        riskMap.put("highRisk", "低危");
                    } else if (score >= 25 && score <= 45) {
                        riskMap.put("highRisk", "中危");
                    } else if (score > 45) {
                        riskMap.put("highRisk", "高危");
                    }
                } else {
                    riskMap.put("highRisk", "无");
                }
                riskMap.put("fileDate", item.get("fileDate"));
                riskMap.put("highRiskData", item.get("highRisk"));
                riskMap.put("fileDateModify", item.get("fileDateModify"));
                riskMap.put("tplName", item.get("tplName"));
                String tplName = item.get("tplName");
                Integer score = Integer.parseInt(item.get("highRisk"));
                if (item.get("highRisk") != null) {//危险程度
                    if ("Morse跌倒评分".equals(tplName)) {//跌倒
                        if (score >= 45) {
                            riskMap.put("highRisk", "高危");
                        } else if (score >= 25 && score <= 44) {
                            riskMap.put("highRisk", "中危");
                        } else if (score < 25) {
                            riskMap.put("highRisk", "高危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("儿童跌倒/坠床评分".equals(tplName)) {//跌倒
                        if (score >= 12) {
                            riskMap.put("highRisk", "高危");
                        } else if (score < 12) {
                            riskMap.put("highRisk", "低危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("Braden评分".equals(tplName)) {//braden
                        if (score <= 9) {
                            riskMap.put("highRisk", "高危");//极高危
                        } else if (score >= 10 && score <= 12) {
                            riskMap.put("highRisk", "高危");
                        } else if (score >= 13 && score <= 14) {
                            riskMap.put("highRisk", "中危");
                        } else if (score >= 15 && score <= 18) {
                            riskMap.put("highRisk", "低危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("Braden-Q评分".equals(tplName) && (score <= 10 || (score >= 11 && score <= 16))) {
                        if (score <= 10) {
                            riskMap.put("highRisk", "高危");//极高危
                        } else if (score >= 11 && score <= 16) {
                            riskMap.put("highRisk", "高危");
                        } else if (score >= 17 && score <= 21) {
                            riskMap.put("highRisk", "中危");
                        } else if (score >= 22) {
                            riskMap.put("highRisk", "低危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("Barthel评分".equals(tplName) && score <= 40) {
                        if (score <= 40) {
                            riskMap.put("highRisk", "高危");//重度依赖
                        } else if (score >= 41 && score <= 60) {
                            riskMap.put("highRisk", "中危");//中度依赖
                        } else if (score >= 61 && score <= 99) {
                            riskMap.put("highRisk", "低危");//轻度依赖
                        } else if (score == 100) {
                            riskMap.put("highRisk", "");//无需依赖
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("营养风险筛查NRS2002评分".equals(tplName) && score >= 3) {
                        if (score >= 3) {
                            riskMap.put("highRisk", "高危");//重度
                        } else if (score == 2) {
                            riskMap.put("highRisk", "中危");//中度
                        } else if (score == 1) {
                            riskMap.put("highRisk", "低危");//轻度
                        } else if (score == 0) {
                            riskMap.put("highRisk", "");//正常
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("导管滑脱危险因素评分".equals(tplName) && score > 12) {
                        if (score > 12) {
                            riskMap.put("highRisk", "高危");
                        } else if (score >= 8 && score <= 12) {
                            riskMap.put("highRisk", "中危");
                        } else if (score < 8) {
                            riskMap.put("highRisk", "低危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("Caprini评分".equals(tplName) && (score >= 5 || (score >= 3 && score <= 4))) {
                        if (score >= 5) {
                            riskMap.put("highRisk", "高危");
                        } else if (score >= 3 && score <= 4) {
                            riskMap.put("highRisk", "中危");
                        } else if (score >= 1 && score <= 2) {
                            riskMap.put("highRisk", "低危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    }else if ("Padua评分".equals(tplName) && (score >= 4 || (score >= 0 && score <= 3))) {
                        if (score >= 4) {
                            riskMap.put("highRisk", "高危");
                        } else if (score >= 0 && score <= 3) {
                            riskMap.put("highRisk", "低危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    }
                } else {
                    riskMap.put("highRisk", "");
                }
                if ("Morse跌倒评分".equals(tplName) && score >= 45) {//跌倒
                    riskMap.put("highRiskName", "跌");
                } else if ("儿童跌倒/坠床评分".equals(tplName) && score >= 12) {//跌倒
                    riskMap.put("highRiskName", "跌");
                } else if ("Braden评分".equals(tplName) && (score <= 9 || (score >= 10 && score <= 12) || (score >= 13 && score <= 14))) {//braden
                    riskMap.put("highRiskName", "压");
                } else if ("Braden-Q评分".equals(tplName) && (score <= 10 || (score >= 11 && score <= 16) || (score >= 17 && score <= 21))) {
                    riskMap.put("highRiskName", "压");
                } else if ("Barthel评分".equals(tplName) && score <= 40) {
                    riskMap.put("highRiskName", "自");
                } else if ("营养风险筛查NRS2002评分".equals(tplName) && score >= 3) {
                    riskMap.put("highRiskName", "");
                } else if ("导管滑脱危险因素评分".equals(tplName) && score > 12) {
                    riskMap.put("highRiskName", "管");
                } else if (("Caprini评分".equals(tplName) && (score >= 5 || (score >= 3 && score <= 4))) || ("Padua评分".equals(tplName) && score >= 4) ) {
                    riskMap.put("highRiskName", "栓");
                } else {
                    riskMap.put("highRiskName", "");
                }
                if (StringUtils.isNotBlank(riskMap.get("highRiskName"))) {
                    riskList.add(riskMap);
                }
            }
        });
        if (riskList != null && riskList.size() > 0) {
            riskList.sort((a, b) -> (int) (DateUtil.stringToDate(a.get("fileDateModify"), "yyyy-MM-dd HH:mm:ss").getTime() / 1000) - (int) (DateUtil.stringToDate(b.get("fileDateModify"), "yyyy-MM-dd HH:mm:ss").getTime() / 1000));
        }
        return riskList;
    }

    @Override
    public Result getDepts() {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        List<Map<String, String>> deptList = transfusionMapper.getDepts(userId,null,null);
        return ResultGenerator.genOkResult(deptList);
    }

    public Result getDepts2(String id,Integer page,Integer pageSize,String keyWords){
        PageHelper.startPage(page, pageSize);
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        List<Map<String, String>> deptList = transfusionMapper.getDepts(userId,id,keyWords);
        PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(deptList);
        return ResultGenerator.genOkResult(pageInfo);

    }

    @Override
    public Result getExamList(String inpatNum, String times, String type, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<PatientExamListVO> examList = patientMapper.queryExamList(inpatNum, times, type, null);
        PageInfo pageInfo = new PageInfo<>(examList);
        return ResultGenerator.genOkResult(pageInfo);
    }

    @Override
    public Result getExamDetail(String examItemId, String reqNum, String inpatNum) {
        PatientExamDetailVO examDetailVO = null;
        if (StringUtils.isNotBlank(examItemId)) {
            PatientExamDetailVO examItemDetailVo = this.patientMapper.getExamItemDetail(examItemId);
            examItemDetailVo.setReqDoctor(examItemDetailVo.getCreatePerson());
            examItemDetailVo.setReportDoctor(examItemDetailVo.getReportUser());
            if (Objects.isNull(examItemDetailVo)) {
                throw new RuntimeException("检查不存在");
            }
            examDetailVO = this.patientMapper.getExamReportDetail(examItemDetailVo.getReqNum(), examItemDetailVo.getSerialNumber());
            if (Objects.isNull(examDetailVO)) {
                examDetailVO = new PatientExamDetailVO();
            }
            examDetailVO.setExamItemName(examItemDetailVo.getExamItemName());
            examDetailVO.setReqDoctor(examItemDetailVo.getReqDoctor());
            examDetailVO.setReportDoctor(examItemDetailVo.getReportDoctor());
            examDetailVO.setAuditDoctor(examItemDetailVo.getAuditDoctor());
            examDetailVO.setReqTime(examItemDetailVo.getReqTime());
            examDetailVO.setReportTime(examItemDetailVo.getReportTime());
            examDetailVO.setExamClass(examItemDetailVo.getExamClass());
        } else if (StringUtils.isNotBlank(reqNum)) {
            examDetailVO = this.patientMapper.getExamReportDetail(reqNum, 1);
            if (Objects.isNull(examDetailVO)) {
                examDetailVO = new PatientExamDetailVO();
            }
            List<PatientExamListVO> examList = patientMapper.queryExamList(inpatNum, null, null, reqNum);
            if (!CollectionUtils.isEmpty(examList)) {
                examDetailVO.setReqTime(examList.get(0).getReqDateTime());
                examDetailVO.setExamClass(examList.get(0).getExamClass());
                examDetailVO.setExamItemName(examList.get(0).getExamItemName());
                examDetailVO.setReqDoctor(examList.get(0).getReqDoctor());
            }
        }

        return ResultGenerator.genOkResult(examDetailVO);
    }


    @Override
    public Result getLabList(String inpatNum, String type, String times, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<PatientLabListVO> labList = patientMapper.queryLabList(inpatNum, type, times);
        PageInfo pageInfo = new PageInfo<>(labList);
        return ResultGenerator.genOkResult(pageInfo);
    }

    @Override
    public Result geLabDetail(String labItemId) {
        // 获取检验详情
        PatientLabDetailVO vo = new PatientLabDetailVO();
        PatientLabTopDetailVO topDetailVO = this.patientMapper.getLabDetail(labItemId);
        // 获取检验报告详情
        vo.setLabReportDate(topDetailVO.getLabReportDate());
        vo.setSepcimenCategory(topDetailVO.getSepcimenCategory());
        List<PatientLabReportDetailVO> reportDetailVoList = this.patientMapper.getLabReportDetail(topDetailVO.getReqNum(), topDetailVO.getSerialNumber());
        if (!CollectionUtils.isEmpty(reportDetailVoList)) {
            vo.setReportDetailList(reportDetailVoList);
        }

        return ResultGenerator.genOkResult(vo);
    }

    @Override
    public Map<String, String> getPatientInfoWithComputeAge(String inpatNum) {
        if (StringUtils.isBlank(inpatNum)) {
            return new HashMap<>();
        }
        //根据入院号获取当前病人信息（姓名，入院号，年龄，床号，性别）
        Map<String, String> patientMap = transfusionMapper.queryPatientInfo(inpatNum);
        if (patientMap == null) {
            return null;
        }
        if (CollectionUtils.isEmpty(patientMap)) {
            patientMap.put("age", "");
        } else {
            // 添加年龄
            patientMap.put("age", DateUtil.getAge(new AgeDTO(patientMap)));
        }
        return patientMap;
    }

    @Override
    public Map<String, String> getPatientInfoNurse(String inpatNum, String wardId, String keyWords, String orgId, String circulationlLogId) {
        //PC端打印腕带时不带-1
        if (inpatNum.indexOf("-1") < 0) {
            inpatNum = inpatNum + "-1";
        }
        Map<String, String> patient = new HashMap<String, String>();
        if (StringUtils.isNotBlank(circulationlLogId)) {
            patient = patientInHospitalMapper.getPatientInfoNurseByLogId(inpatNum, wardId, keyWords, circulationlLogId);
        } else {
            patient = patientInHospitalMapper.getPatientInfoNurse(inpatNum, wardId, keyWords);
        }


        //Map<String,String> patient = patientInHospitalMapper.getPatientInfoNurse(inpatNum,wardId,keyWords);
        if (patient == null)
            return patient;
        getPatientAge(patient);

        //费别 注释的是正式参数与返回
        String url = cost;
        Map<String, Object> param = new HashMap<>();
        param.put("as_patientId", inpatNum.replace("-1", ""));
        param.put("operationID", "10001");
        param.put("al_visitId", "1");
        param.put("al_doctor_type", "");
        CompletableFuture<String> ordedCustomerFuture = CompletableFuture.supplyAsync(() ->
                HttpClientUtil.sendPost(url, param)).thenApply(x -> x.toString());
        try {
            JSONObject jsonObject = JSON.parseObject(ordedCustomerFuture.get());
            if (jsonObject.getString("data") != null) {
                Map cost = JSONArray.parseArray(jsonObject.getString("data"), Map.class).get(0);
                if (cost.get("CHARGE_TYPE").toString().contains("自费")) {
                    patient.put("payOff", "自费");
                } else {
                    patient.put("payOff", cost.get("CHARGE_TYPE").toString());
                }
            }
        } catch (Exception e) {
            log.error("查询费用明细失败", e);
        }

        if (StringUtils.isBlank(patient.get("inBedNo")))
            patient.put("inBedNo", "");
        if (StringUtils.isBlank(patient.get("outBedNo")))
            patient.put("outBedNo", "");
        //查询手术转运方式
        if (MapUtils.isNotBlack(patient) && StringUtils.isNotBlank(orgId)) {
            CirculationLogEntity circulationLogEntity = circulationLogMapper.selectNewLogByInpatNumAndType(inpatNum, CirculationTypeEnum.OPERATION.getCode(), orgId, CirculationModelEnum.FINISH_IN_OPERATION.getCode());
            if (null != circulationLogEntity) {
                patient.put("transferType", circulationLogEntity.getRemark());
            }
        }

        Map<String, String> map = circulationLogMapper.queryDischargeDiagnosisByInpatNum(inpatNum);
        if(map!=null){
            patient.put("leaveHospitalDiagId",map.get("DIAG_ID")!=null?map.get("DIAG_ID"):"");
            patient.put("leaveHospitalDiagName",map.get("DIAG_NAME")!=null?map.get("DIAG_NAME"):"");
            patient.put("leaveHospitalDiagIcd",map.get("DIAG_ICD")!=null?map.get("DIAG_ICD"):"");
        }
        return patient;
    }

    private void getPatientAge(Map<String, String> patientInfo) {
        Integer ageYear = patientInfo.get("ageYear") == null ? 0 : Integer.parseInt(patientInfo.get("ageYear"));
        Integer ageMonth = patientInfo.get("ageMonth") == null ? 0 : Integer.parseInt(patientInfo.get("ageMonth"));
        Integer ageDay = patientInfo.get("ageDay") == null ? 0 : Integer.parseInt(patientInfo.get("ageDay"));
        Integer ageHour = patientInfo.get("ageHour") == null ? 0 : Integer.parseInt(patientInfo.get("ageHour"));
        Integer ageMinute = patientInfo.get("ageMinute") == null ? 0 : Integer.parseInt(patientInfo.get("ageMinute"));
        StringBuffer ageStr = new StringBuffer();
        if (ageYear != 0) {
            ageStr.append(ageYear + "岁");
        }
        if (ageMonth != 0) {
            ageStr.append(ageMonth + "月");
        }
        if (ageDay != 0) {
            ageStr.append(ageDay + "天");
        }
        if (ageHour != 0) {
            if (ageDay < 29) {              //28天以上不需要小时
                ageStr.append(ageHour + "小时");
            }
        }
        if (ageMinute != 0) {
            ageStr.append(ageMinute + "分钟");
        }
        if (ageStr.length() == 0) {
            ageStr.append(ageHour + "小时");
            ageStr.append(ageMinute + "分钟");
        }
        patientInfo.put("age", ageStr.toString());
    }

    private String getPatientAgeOPbject(Map<String, Object> patientInfo) {
        Integer ageYear = patientInfo.get("ageYear") == null ? 0 : Integer.parseInt(patientInfo.get("ageYear").toString());
        Integer ageMonth = patientInfo.get("ageMonth") == null ? 0 : Integer.parseInt(patientInfo.get("ageMonth").toString());
        Integer ageDay = patientInfo.get("ageDay") == null ? 0 : Integer.parseInt(patientInfo.get("ageDay").toString());
        Integer ageHour = patientInfo.get("ageHour") == null ? 0 : Integer.parseInt(patientInfo.get("ageHour").toString());
        Integer ageMinute = patientInfo.get("ageMinute") == null ? 0 : Integer.parseInt(patientInfo.get("ageMinute").toString());
        StringBuffer ageStr = new StringBuffer();
        if (ageYear != 0) {
            ageStr.append(ageYear + "岁");
        }
        if (ageMonth != 0) {
            ageStr.append(ageMonth + "月");
        }
        if (ageDay != 0) {
            ageStr.append(ageDay + "天");
        }
        if (ageHour != 0) {
            if (ageDay < 29) {              //28天以上不需要小时
                ageStr.append(ageHour + "小时");
            }
        }
        if (ageMinute != 0) {
            ageStr.append(ageMinute + "分钟");
        }
        if (ageStr.length() == 0) {
            ageStr.append(ageHour + "小时");
            ageStr.append(ageMinute + "分钟");
        }
        patientInfo.put("age", ageStr.toString());
        return ageStr.toString();
    }

    public String getDiagName(String inpatNum) {
        // 过滤诊断
        // 获取护士修改后绑定到文书的诊断id
        String diagName = "";
        String diagId = patientMapper.queryDiagIdByInpatNum(inpatNum);
        if (StringUtils.isNotBlank(diagId)) {
            // 获取护士修改的诊断名称
            diagName = patientMapper.queryDiagByDiagId(diagId);
            return diagName;
        } else {
            //取病案首页his出院诊断
            if ("prod".equals(activeType)) {
                String[] inpatNums = inpatNum.split("-");
                String param = "as_patient_id=" + inpatNums[0] + "&al_visit_id=" + inpatNums[1];
                JSONObject jsonObject = HttpConnectUtils.sendGet("http://172.20.91.56:8181/P_VsitInfo_Query_03", param);
                if ("1".equals(jsonObject.get("error_id").toString())) {
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    for (Object jsonObject1 : jsonArray) {
                        JSONObject object = JSONObject.parseObject(jsonObject1.toString());
                        if (object.get("DIAGNOSIS_TYPE") != null && "2".equals(object.get("DIAGNOSIS_TYPE").toString())) {
                            diagName = object.get("DIAGNOSIS_DESC").toString();
                            break;
                        }
                    }
                }
            }
            if (StringUtils.isNotBlank(diagName)) {
                return diagName;
            } else {
                // 获取智慧病历出院诊断/修正诊断/入院诊断
                diagName = patientMapper.queryOutHospitalDiag(inpatNum);
                if (StringUtils.isNotBlank(diagName)) {
                    return diagName;
                } else {
                    //获取his门诊诊断
                    diagName = patientMapper.queryOutpatientDiag(inpatNum);
                    return diagName;
                }
            }
        }
    }

    public Result queryExamAppointment(String dateTime,String type,String wardDeptId,String checkDeptId,String keyWords,Integer page,Integer pageSize){
        //0未预约 1已预约 2已检查
        String allInpatNum = null;
        if("0".equals(type) || "1".equals(type)) {
            allInpatNum = mealListMapper.queryPatientMedicalNumByWardDeptId(wardDeptId, null, keyWords);
        }
        PageHelper.startPage(page,pageSize);
        //获取检查列表
        List<Map<String, String>> list = patientMapper.getExamArrangement(dateTime,type,wardDeptId,checkDeptId,keyWords,allInpatNum);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genOkResult(pageInfo);
    }

    public Result queryCheckDept(String dateTime,String type,String wardDeptId,String checkDeptId,String keyWords){
        String allInpatNum = null;
        if("0".equals(type) || "1".equals(type)) {
            allInpatNum = mealListMapper.queryPatientMedicalNumByWardDeptId(wardDeptId, null, keyWords);
        }
        //获取检查科室
        List<Map<String, String>> checkDeptList = patientMapper.getCheckDept(dateTime,type,wardDeptId,checkDeptId,keyWords,allInpatNum);
        return ResultGenerator.genOkResult(checkDeptList);
    }

    public Result queryExamAppointmentPrint(String dateTime,String type,String wardDeptId,String checkDeptId,String keyWords,String patexamreportdataIds,Integer page,Integer pageSize){
        String allInpatNum = null;
        if("0".equals(type) || "1".equals(type)) {
            allInpatNum = mealListMapper.queryPatientMedicalNumByWardDeptId(wardDeptId, null, keyWords);
        }
        PageHelper.startPage(page,pageSize);
        //获取检查列表
        List<PatientExamDTO> examArrangementPrint = patientMapper.getExamArrangementPrint(dateTime, type, wardDeptId, checkDeptId, keyWords, allInpatNum,patexamreportdataIds);
        PageInfo pageInfo = new PageInfo(examArrangementPrint);
        return ResultGenerator.genOkResult(pageInfo);
    }


    @Override
    public Result queryDailyReport(String deptCode, String startDatetime, String endDatetime) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        Map<String, String> deptMap = patientInHospitalMapper.queryDeptCodeByDeptId2(deptCode);
        String personCode = patientInHospitalMapper.queryPersonCodeByUserId(userId);
        String operationDate = DateUtil.dateToString(new java.util.Date(), "yyyy-MM-dd HH:mm");
        String params = "{" +
                "    'operationID': '" + ConstantEnum.HZQUERY_10015.getKey() + "'," +
                "    'c_request': {" +
                "       'request': {" +
                "            'source': '3'," +
                "            'hospital_no': '"+deptMap.get("hospitalAreaNo")+"'," +
                "            'operator': '" + personCode + "'," +
                "            'operationdate': '" + operationDate + "'," +
                "            'dept_code':'" + deptMap.get("deptCode") + "'," +
                "            'starttime':'" + startDatetime + "'," +
                "            'endtime':'" + endDatetime + "'" +
                "        }" +
                "    }" +
                "}";
        log.info("操作码:{}-{}", ConstantEnum.HZQUERY_10015.getKey(), params);
        String resultString = HttpClientUtil.sendPostByJson(hisQueryUrl, params);
        log.info("操作码:{}-result-{}", ConstantEnum.HZQUERY_10015.getKey(), resultString);
        JSONObject jsonObject = JSONObject.parseObject(resultString);
        if (!jsonObject.getString("Error_Id").equals(ConstantEnum.HIS_ERROR_CODE_1.getKey())) {
            return ResultGenerator.genFailedResult("查询出错：" + jsonObject.getString("Error_Msg"));
        }
        return ResultGenerator.genOkResult(jsonObject.getJSONObject("c_response").getJSONObject("response"));
    }

    @Override
    public Result getPatientPeopleDetail(String inpatNum) {
        Map<String, String> patientInfo = patientMapper.findPatientById(inpatNum);

        if(CollectionUtils.isEmpty(patientInfo)){
            return ResultGenerator.genFailedResult("患者信息不存在");
        }
        PatientConfirmDateEntity patientConfirmDateEntity = patientConfirmDateMapper.selectByInpatNum(inpatNum);
        if(null != patientConfirmDateEntity){
            patientInfo.put("confirmFlag","false");
        }else{
            patientInfo.put("confirmFlag","true");
        }
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if(patientInfo.get("inDatetime") != null){
                String startDate = patientInfo.get("inDatetime");
                String endDate = "";
                if(patientInfo.get("outDatetime")==null){
                    endDate = sdf.format(new Date(new Date().getTime()+(1000*60*60*24)));//未出院
                }else{
                    endDate = patientInfo.get("outDatetime");//已出院
                }
                Date startTime = sdf.parse(startDate);
                Date endTime = sdf.parse(endDate);
                Long longTime = endTime.getTime() - startTime.getTime();
                BigDecimal daysDecimal = new BigDecimal(longTime).divide(new BigDecimal(1000*60*60*24));
                int days = daysDecimal.intValue();//出院当天不算住院天数
                patientInfo.put("inHospitalDays", Integer.toString(days));
            }
        }catch (Exception e){
            log.error("病人信息:时间解析错误{}",e);
        }
        if (patientInfo.get("wardName") == null)
            patientInfo.put("wardName", "无");
        if (patientInfo.get("inHospitalDays") == null)
            patientInfo.put("inHospitalDays", "0");
        if (patientInfo.get("deptName") == null)
            patientInfo.put("deptName", "无");
        //拼接年龄
        getPatientAge(patientInfo);
        //护理等级
        String dateTime = DateUtil.dateToString(new Date(),"yyyy-MM-dd");
        List<String> nursingGradeList = Arrays.asList(VarCodeEnum.IJHL.getVarCode(), VarCodeEnum.IJHLEK.getVarCode(), VarCodeEnum.IIJHL.getVarCode(),
                VarCodeEnum.IIIJHLEK.getVarCode(), VarCodeEnum.IIIJHL.getVarCode(), VarCodeEnum.IIIJHLEK.getVarCode(),
                VarCodeEnum.YJHL.getVarCode(), VarCodeEnum.EJHL.getVarCode(), VarCodeEnum.SJHL.getVarCode(),
                VarCodeEnum.TJHL.getVarCode(), VarCodeEnum.TJHLEK.getVarCode(), VarCodeEnum.JHBFYJHL.getVarCode(),
                VarCodeEnum.JHBFEJHL.getVarCode(), VarCodeEnum.JHBFTJHL.getVarCode());
        List<String> disdaseStateList = Arrays.asList(VarCodeEnum.BINGWEI.getVarCode(), VarCodeEnum.BINGZHONG.getVarCode());
        List<Map<String, String>> nursingGradeLists = mealListMapper.queryNursingGradeByInpatNum(Arrays.asList(inpatNum), dateTime,nursingGradeList);
        List<Map<String, String>> disdaseStateLists = mealListMapper.queryNursingGradeByInpatNum(Arrays.asList(inpatNum), dateTime,disdaseStateList);
        AtomicReference<String> nursingGrade= new AtomicReference<>("无");
        nursingGradeLists.forEach(filterNursingGrade -> {
            if (VarCodeEnum.TJHL.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.TJHLEK.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.JHBFTJHL.getVarCode().equals(filterNursingGrade.get("varCode"))) {
                nursingGrade.set(VarCodeEnum.TJHL.getName());
            } else if (VarCodeEnum.IJHL.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.IJHLEK.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.YJHL.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.JHBFYJHL.getVarCode().equals(filterNursingGrade.get("varCode"))) {
                nursingGrade.set(VarCodeEnum.YJHL.getName());
            } else if (VarCodeEnum.IIJHL.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.IIJHLEK.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.EJHL.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.JHBFEJHL.getVarCode().equals(filterNursingGrade.get("varCode"))) {
                nursingGrade.set(VarCodeEnum.EJHL.getName());
            } else if (VarCodeEnum.IIIJHL.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.IIIJHLEK.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.SJHL.getVarCode().equals(filterNursingGrade.get("varCode"))) {
                nursingGrade.set(VarCodeEnum.SJHL.getName());
            }
        });
        patientInfo.put("nursingGrade",nursingGrade.get());


        return ResultGenerator.genOkResult(patientInfo);
    }

    @Override
    public Result getPatientPeopleDetailFromHis(String inpatNum) {
        Map<String, String> patientInfo = new HashMap<>();
        /*String url = this.hisUrl + "/emrnew/HospitalSelfHelpInterface";
        Map<String, Object> param = new HashMap<>();
        param.put("as_patientId", inpatNum.replace("-1", ""));
        param.put("operationID", "10001");
        param.put("al_visitId", "1");
        param.put("al_doctor_type", "");
        try {
            JSONObject jsonObject = HttpClientUtil.sendPost(url, param);
            if (jsonObject.getString("data") != null) {
                Map cost = JSONArray.parseArray(jsonObject.getString("data"), Map.class).get(0);
                String aScale = StringUtils.isEmpty((String) cost.get("A_SCALE")) ? "0" : (String) cost.get("A_SCALE");
                cost.put("A_SCALE", Double.parseDouble(aScale));
                String lScale = StringUtils.isEmpty((String) cost.get("L_SCALE")) ? "0" : (String) cost.get("L_SCALE");
                cost.put("L_SCALE", Double.parseDouble(lScale));
                String paidCost = StringUtils.isEmpty((String) cost.get("YJJ_AMT")) ? "0" : (String) cost.get("YJJ_AMT");
                cost.put("YJJ_AMT", paidCost);
                String totalCost = StringUtils.isEmpty((String) cost.get("TOTAL_COST")) ? "0" : (String) cost.get("TOTAL_COST");
                cost.put("TOTAL_COST", totalCost);
                String balance = StringUtils.isEmpty((String) cost.get("YE_JE")) ? "0" : (String) cost.get("YE_JE");
                cost.put("BALANCE", balance);
                if ("自费   自费".equals((String) cost.get("CHARGE_TYPE"))) {
                    cost.put("CHARGE_TYPE", "自费");
                }
                patientInfo.putAll(cost);
            }
        } catch (Exception e) {
            log.error("查询费用明细失败。", e);
        }*/
        return ResultGenerator.genOkResult(patientInfo);
    }


}
